package socket;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.WebSocket;
import io.vertx.core.http.impl.WebSocketImpl;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.WebClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyVerticle5 extends AbstractVerticle {

	@Override
	public void start() throws Exception {
		String token = "fb0eca8aea07075cfe7588a46209366b";
//		vertx.createHttpClient().webSocket(8888,"localhost","/jetlinks/messaging/"+token+"?:X_Access_Token="+token, res -> {
		vertx.createHttpClient().webSocket(8848,"localhost","/messaging/"+token, res -> {
			if (res.succeeded()) {
				WebSocket ws = res.result();
				System.out.println("client received!" + ws.toString());

				WebSocketImpl ws2 = (WebSocketImpl) ws;
				String textId = ws2.textHandlerID();
				String binId = ws2.binaryHandlerID();

				//订阅消息
				MessagingRequest mr = new MessagingRequest();
				mr.setId(textId);
				mr.setType(MessagingRequest.Type.sub);
				mr.setTopic("/device/*/*/**");

				Map<String,Object> parameter = new HashMap<>();
				parameter.put("messageType","READ_PROPERTY");
				List<String> propList = new ArrayList<>();
				propList.add("SR");
				parameter.put("properties",propList);
//				Map<String,Object> headers = new HashMap<>();
//				headers.put("async", false);
//				parameter.put("headers",headers);
				mr.setParameter(parameter);
//				Buffer buffer = JsonObject.mapFrom(mr).toBuffer();

				ws.writeTextMessage(JsonObject.mapFrom(mr).toString(), result -> {
					if (result.succeeded()) {
						System.out.println('1');
					} else {
						res.cause().printStackTrace();
					}
				});

//				ws.close();
			}else{
				res.cause().printStackTrace();
			}
		});
	}

	public static void main(String[] args) {
		VertxOptions o = new VertxOptions();
		Vertx vertx = Vertx.vertx();
		vertx.deployVerticle(new MyVerticle5());
	}
}
